<template>
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" size="1000" @close="handleClose">
        <el-form :model="formData" ref="formRef" :rules="rules" label-position="right" label-width="80px" size="default"
            :scroll-to-error="true" :show-message="false">
            <el-form-item label="车型" prop="vehicle_id" class="required label-right-align" label-width="120px">
                <el-select-v2 v-model="formData.vehicle_id" clearable :options="vehicles" :props="{
                    label: 'model',
                    value: 'id'
                }" :fit-input-width="600" style="width: 200px;" placeholder="请选择车型">
                    <template v-slot:header>
                        <el-select v-model="vehicles_search.brands" placeholder="按品牌筛选" clearable>
                            <el-option v-for="(item, index) in brands" :key="index" :label="item"
                                :value="item"></el-option>
                        </el-select>
                        <div class="letter-box">
                            <div class="letter-item" :class="{ 'active': item == vehicles_search.firstletter }"
                                v-for="(item, index) in letter" :key="index" @click="setLetter(item)">{{ item }}
                            </div>
                        </div>
                        <el-input v-model="vehicles_search.keyword" placeholder="搜索车型" clearable
                            prefix-icon="Search"></el-input>
                        <div class="count-box">
                            <div class="count-num">找到{{ vehicles.length }}个车型</div>
                            <el-button @click="vehicles_search.is_popular = !vehicles_search.is_popular" type="warning"
                                icon="Star" size="small" :plain="!vehicles_search.is_popular">只看热门</el-button>
                        </div>
                    </template>
                </el-select-v2>
            </el-form-item>
            <el-form-item label="产品" prop="product_id" class="required label-right-align" label-width="120px">
                <el-select v-model="formData.product_id" placeholder="选择产品" style="width: 200px;">
                    <template #header>
                        <el-tag :type="produtType == '窗膜' ? 'primary' : 'info'"
                            @click="produtType = produtType == '窗膜' ? '' : '窗膜'">窗膜</el-tag>
                        <el-tag :type="produtType == '车衣' ? 'primary' : 'info'" style="margin-left: 10px;"
                            @click="produtType = produtType == '车衣' ? '' : '车衣'">车衣</el-tag>
                    </template>
                    <el-option v-for="item in showProductOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="整套价格" prop="base_price" class="required label-right-align" label-width="120px">
                <el-input-number v-model="formData.base_price" :style="{ width: '300px' }"></el-input-number>
            </el-form-item>
            <el-form-item label="折扣率" prop="discount_rate" class="label-right-align" label-width="120px">
                <el-slider v-model="formData.discount_rate" style="width: 300px;"></el-slider>
            </el-form-item>
            <el-form-item label="生效日期" prop="effective_date" class="label-right-align" label-width="120px">
                <el-date-picker v-model="formData.effective_date" type="date" placeholder="选择生效日期"
                    style="width: 200px;"></el-date-picker>
            </el-form-item>
            <el-divider content-position="left">组件价格</el-divider>
            <el-tabs v-model="priceTag" type="card">
                <el-tab-pane label="部位价格" name="PART">
                    <el-table :data="partPrices" border stripe>
                        <el-table-column label="部位名称">
                            <template #default="scope">
                                <el-input v-model="scope.row.component_key" placeholder="部位名称"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="价格">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.price"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button @click="removePartPrice(scope.$index)" icon="Delete"
                                    type="danger"></el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button @click="addPartPrice" icon="Plus" type="primary">添加部位价格</el-button>
                </el-tab-pane>
                <el-tab-pane label="套餐价格" name="PACKAGE">
                    <el-table :data="packagePrices" border stripe>
                        <el-table-column label="套餐名称">
                            <template #default="scope">
                                <el-input v-model="scope.row.component_key" placeholder="套餐名称"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="价格">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.price"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button @click="removePackagePrice(scope.$index)" icon="Delete"
                                    type="danger"></el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button @click="addPackagePrice" icon="Plus" type="primary">添加套餐价格</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogClose">取消</el-button>
                <el-button type="primary" @click="submitForm"> 提交 </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose, defineEmits, onMounted, inject, computed } from "vue";
import { ElMessage } from "element-plus";
import { addPriceApi, editPriceApi } from "@/api/carfilm/quote";
const dialogFormVisible = ref(false);
const formRef = ref<any>(null);
const dialogTitle = ref("");
const vehicles_search = ref({
    brands: "",
    firstletter: "",
    is_popular: false,
    keyword: ""
})
const allVehicles = inject("allVehicles") as any;
const vehicles = computed(() => {
    return allVehicles.value.filter((item: any) => {
        if (vehicles_search.value.brands) {
            if (item.brand != vehicles_search.value.brands) {
                return false;
            }
        }
        if (vehicles_search.value.firstletter) {
            if (item.firstletter != vehicles_search.value.firstletter) {
                return false;
            }
        }
        if (vehicles_search.value.is_popular) {
            if (item.is_popular != vehicles_search.value.is_popular) {
                return false;
            }
        }
        if (vehicles_search.value.keyword) {
            if (!item.model.includes(vehicles_search.value.keyword)) {
                return false;
            }
        }
        return true;
    })
})
const brands = computed(() => {
    let val = allVehicles.value.map((item: any) => {
        return item.brand;
    });
    //去重
    return val.filter((item: any, index: number) => {
        return val.indexOf(item) === index;
    });
});
const letter = ref(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]);
const setLetter = (letter: string) => {
    if (vehicles_search.value.firstletter == letter) {
        vehicles_search.value.firstletter = "";
    }
    else {
        vehicles_search.value.firstletter = letter;
    }
};
const productOptions = inject("productOptions") as any;
const produtType = ref("");
const showProductOptions = computed(() => {
    return productOptions.value.filter((item: any) => {
        if (produtType.value) {
            if (item.type != produtType.value) {
                return false;
            }
        }
        return true;
    })
})
const priceTag = ref("PART");
const formData = ref({
    id: 0,
    vehicle_id: 0,
    product_id: "",
    base_price: 0,
    discount_rate: 100,
    effective_date: "",
    components: [] as any[],
});
const partPrices = ref<any[]>([]);
const packagePrices = ref<any[]>([]);
const addPartPrice = () => {
    partPrices.value.push({
        component_key: "",
        price: 0,
    });
};
const removePartPrice = (index: number) => {
    partPrices.value.splice(index, 1);
};
const addPackagePrice = () => {
    packagePrices.value.push({
        component_key: "",
        price: 0,
    });
};
const removePackagePrice = (index: number) => {
    packagePrices.value.splice(index, 1);
};
const rules = reactive({
    vehicle_id: [
        {
            required: true,
            message: "请选择车型",
        },
    ],
    product_id: [
        {
            required: true,
            message: "请选择车型",
        },
    ],
    base_price: [
        {
            required: true,
            message: "请填写价格",
        },
    ],
});

const emits = defineEmits(["getTable"]);
function addSave() {
    addPriceApi(formData.value)
        .then((res) => {
            ElMessage.success("添加成功");
            emits("getTable");
            dialogClose();
        })
        .catch((err) => { });
}
function editSave() {
    editPriceApi(formData.value)
        .then((res) => {
            ElMessage.success("编辑成功");
            emits("getTable");
            dialogClose();
        })
        .catch((err) => { });
}

function submitForm() {
    formRef.value.validate().then(() => {
        formData.value.components = [...partPrices.value, ...packagePrices.value];
        if (formData.value.id == 0) {
            addSave();
        } else {
            editSave();
        }
    });
}

const dialogClose = () => {
    dialogFormVisible.value = false;
};

const dialogOpen = (info?: any) => {
    dialogFormVisible.value = true;
    if (info?.id > 0) {
        dialogTitle.value = "编辑价格策略";
        formData.value = {
            id: info.id,
            vehicle_id: info.vehicle_id,
            product_id: info.product_id,
            base_price: parseFloat(info.base_price),
            discount_rate: info.discount_rate * 100,
            effective_date: info.effective_date,
            components: info.components,
        };
        partPrices.value = info.components.filter((item: any) => {
            return item.component_type == "PART";
        });
        packagePrices.value = info.components.filter((item: any) => {
            return item.component_type == "PACKAGE";
        });
    } else {
        dialogTitle.value = "添加价格策略";
    }
};

const handleClose = () => {
    formRef.value.resetFields();
    formData.value = {
        id: 0,
        vehicle_id: 0,
        product_id: "",
        base_price: 0,
        discount_rate: 100,
        effective_date: "",
        components: [] as any[],
    };
    partPrices.value = [];
    packagePrices.value = [];
    dialogFormVisible.value = false;
};

defineExpose({
    dialogOpen,
});
</script>

<style lang="scss">
.el-form-item {
    margin-bottom: 10px;
}
</style>

<style lang="scss" scoped>
.letter-box {
    margin-top: 10px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .letter-item {
        padding: 5px 10px;
        margin-top: 5px;
        cursor: pointer;
        margin-right: 5px;
        border: 1px solid #d9ecff;
        border-radius: 4px;

        &.active {
            background-color: #409eff;
            color: #fff;
        }
    }
}

.count-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
}

.brand-item {
    margin-bottom: 35px;
    background-color: #fff;
    border-radius: 6px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, .05);
    padding: 24px;
    transition: all .3s;

    .brand-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 22px;
        padding-bottom: 12px;
        border-bottom: 1px solid #ebeef5;

        .brand-left {
            display: flex;
            align-items: center;

            .brand-name {
                margin: 0 15px 0 15px;
                font-size: 18px;
                font-weight: 500;
                color: #303133;
            }
        }
    }

}

.tag-box {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin-top: 10px;

    .el-tag {
        margin-right: 5px;
    }
}
</style>
